package com.zhanggm.springboot.demo.controller;

import com.jinping.utils.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class UploadController {

    @Value("${file.path}")
    private String filePath;

    @Value("${file.domain}")
    private String fileDomain;

    @PostMapping("upload")
    public Object upload(@RequestParam("file") MultipartFile file){
        //返回结果
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("result",false);
        resultMap.put("msg","文件上传失败");
        //保存的文件名
        String originalFilename = file.getOriginalFilename();
//        String fileExtName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String fileExtName = FileUtil.getSuffix(originalFilename);
        String fileName = UUID.randomUUID()+fileExtName;
        String fileFullName = filePath+fileName;
        //保存文件
        File saveFile = new File(fileFullName);
        try {
            file.transferTo(saveFile);
            //返回结果
            resultMap.put("result",true);
            resultMap.put("msg","文件上传成功");
            resultMap.put("imgUrl",fileDomain+fileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回文件的访问路径
        return resultMap;
    }
}
